<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>列表</title>
  <style>
      .chatroom{
        width:280px;
        height:420px;
        border:1px solid darkgoldenrod;
        border-radius: 10px;
        padding:10px;
        overflow: auto;
      }
      .text{
        font-size: 14px;
        color:#999;
      }
   </style>
</head>
<body>
    <%- include('head',{title:"聊天室"})%>
  <div class="page">
      <div class="chat">
          <h2>wh2107 聊天室</h2>
          <div class="chatroom" id="chatroom">
    
          </div>
          <div>
            <input type="text" id="word" placeholder="请输入聊天内容">
            <button id="sendbtn">发送</button>
          </div>
      </div>
  </div>
  <%- include foot  %>
  <script>
      // # 客户端的 Socket
      // # 创建客户端的socket 
      // # 链接服务器的socket 
      // # 发送消息到服务器端 
      // # 接收来自服务器的 数据   
      // # 监听服务器的socket 关闭 error
  
      window.onload = function(){
        // # 创建客户端的socket 
        // # 链接服务器的socket 
        const socket = new WebSocket("ws://localhost:3800");
  
        socket.onopen = function(){
          // # 发送消息到服务器端 
          socket.send("大家好,我是你们的一员...")  
        }
  
        // # 接收来自服务器的 数据 
        socket.onmessage = function(data){
          console.log(data)
          var chatroom = document.getElementById("chatroom")
          chatroom.innerHTML += `<p class="text"> ${data.data}</p>`;
        }
        
        function sendMsg(){
            var word = document.getElementById("word");
            socket.send(word.value)
            word.value = "";
        }
  
        sendbtn.onclick = function(){
          sendMsg()
        }
  
        document.onkeydown = function(e){
          if(e.keyCode==13){
            sendMsg()
          }
        }
  
        socket.onclose = function(){
          console.log("服务器突然宕机了...")
        }
  
        socket.onerror = function(){
          console.log("服务器出现异常了...")
        }
      }
    </script>
</body>
</html>